let global_labels;
const max_level = 3;
let edit_mode = 0;

// 延迟执行
function sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time));
}
// 显示弹窗
function showWaitModal() {
    $("#waitModal").modal("show");
}
// 隐藏弹窗
function hideWaitModal() {
    $("#waitModal").modal("hide");
    sleep(500).then(() => {
        $("#waitModal").modal("hide");
    });
}
// 确认操作
function confirmAction(callback, data) {
    const secondary_button = $("#secondary_button");
    secondary_button.show();
    const modal = $("#messageModal");
    modal.find(".modal-title").text("操作确认");
    modal.find(".modal-body p").text("确定要执行此操作吗？");
    const confirm_button = $("#primary_button");
    confirm_button.removeClass("btn-success btn-warning").addClass("btn-primary");
    modal.modal('show');
    confirm_button.off("click");
    confirm_button.on("click", function () {
        $("#messageModal").modal('hide');
        sleep(500).then(() => {
            callback(data);
        });
    });
}
//提示成功或失败
function message(data, success) {
    const secondary_button = $("#secondary_button");
    secondary_button.hide();
    const modal = $("#messageModal");
    const confirm_button = $("#primary_button");
    if (success) {
        modal.find(".modal-title").text("操作成功");
        confirm_button.removeClass("btn-primary btn-warning").addClass("btn-success");
    } else {
        modal.find(".modal-title").text("操作失败");
        confirm_button.removeClass("btn-primary btn-success").addClass("btn-warning");
    }
    modal.find(".modal-body p").text(data);
    hideWaitModal();
    modal.modal("show");
    confirm_button.off("click");
    confirm_button.on("click", function () {
        $("#messageModal").modal('hide');
    });
}
// 添加标签窗口
function addModal(level) {
    const modal = $('#labelModal');
    modal.find(".modal-title").text("添加标签");
    $("#label_id").val("");
    $("#label_name").val("");
    $("#label_info").val("");
    const uplevelId = $("#label_" + level).attr("uplevel");
    $("#label_uplevelId").val(uplevelId);
    // $("#form_uplevelId").show();
    modal.modal('show');
    const save_button = $("#save_button");
    save_button.off("click");
    save_button.on("click", function () {
        $("#labelModal").modal('hide');
        add();
    });
}
// 更新标签窗口
function updateModal(id, name, info) {
    const modal = $('#labelModal');
    modal.find(".modal-title").text("编辑标签");
    $("#label_id").val(id);
    $("#label_name").val(name);
    $("#label_info").val(info);
    // $("#form_uplevelId").hide();
    modal.modal("show");
    const save_button = $("#save_button");
    save_button.off("click");
    save_button.on("click", function () {
        $("#labelModal").modal('hide');
        update();
    });
    const del_btn = $("#del_btn");
    del_btn.off("click");
    del_btn.on("click", function () {
        $("#labelModal").modal('hide');
        confirmAction(del, id);
    });
}
// 添加标签
function add() {
    showWaitModal();
    const name = $("#label_name").val();
    const info = $("#label_info").val();
    const uplevelId = $("#label_uplevelId").val();
    if (name === "" || info === "" || uplevelId === "") {
        message("标签信息不可以为空！", false);
        return;
    }
    const newLabel = {
        labelName: name,
        labelInfo: info,
        uplevelId: uplevelId
    };
    $.ajax({
        type: "post",
        url: "/labels",
        data: newLabel,
        success: function (data) {
            if (data.code === 200)
                message("添加成功。", true);
            else
                message(data.msg, false);
        }, error: function (err) {
            message("添加失败：" + err, false);
        }
    });
}
// 删除标签
function del(id) {
    showWaitModal();
    $.ajax({
        type: "delete",
        url: "/labels/" + id,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.code === 200) {
                //TODO remove button(s) from page
                message("删除成功。", true);
            }
            else
                message(data.msg, false);
        }, error: function (err) {
            message("删除失败：" + err, false);
        }
    });
}
// 更新标签
function update() {
    showWaitModal();
    const id = $("#label_id").val();
    const name = $("#label_name").val();
    const info = $("#label_info").val();
    const updateLabel = {
        labelName: name,
        labelInfo: info
    };
    $.ajax({
        type: "patch",
        url: "/labels/" + id,
        data: updateLabel,
        success: function (data) {
            if (data.code === 200)
                message("更新成功。", true);
            else
                message(data.msg, false);
        }, error: function (err) {
            message("更新失败：" + err, false);
        }
    });
}
// 获取标签
function get(id, next) {
    $.ajax({
        type: "get",
        url: "/labels/" + id,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            // code 200 500?
            if (data.code === 200)
                next(data);
            else
                message(data.msg, false);
        }, error: function (err) {
            message("无法获取标签信息：" + err, false);
        }
    });
}
// 获取所有标签，加载页面的时候执行
function getAll() {
    // showWaitModal();
    if (edit_mode === 1) {
        editMode();
        return;
    }
    $.ajax({
        type: "get",
        url: "/labels",
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            // hideWaitModal();
            // code 200 500?
            if (data.code === 200) {
                global_labels = data.result;
                // showAll(data);
                showLabels(1, 0);
            } else
                message(data.msg, false);
        }, error: function (err) {
            message("无法获取标签列表：" + err, false);
        }
    });
}

function showLabels(level, uplevelId, btn) {
    if (edit_mode === 1) { // 编辑模式
        if (btn !== undefined) {
            let label_id = $(btn).attr("label_id");
            let label_name = $(btn).attr("label_name");
            let label_info = $(btn).attr("label_info");
            updateModal(label_id, label_name, label_info); // 弹出编辑窗口
        }
        return;
    }

    const label_list = $("#label_" + level);

    for (let i = level; i <= max_level; i++) {
        $("#label_" + i).html("");

        $("#label_" + i).removeAttr("uplevel");
    }

    label_list.attr("uplevel", uplevelId);
    let num = 0;
    for (let label of global_labels) {
        if (label.uplevelId === uplevelId) {
            num++;
            label_list.append('<button label_id="'+label.id+'" label_name="'+label.labelName+'" label_info="'+label.labelInfo+'" class="btn btn-default" onclick="showLabels(' + (level + 1) + ', ' + label.id + ', this)">' + label.labelName + '</button>');
        }
    }
    if (num === 0) {
        label_list.append("空");
    }

    if (btn !== undefined) {
        let buttons = $("#label_" + (level-1)).find("button");
        for (let button of buttons) {
            $(button).removeClass("btn-info").addClass("btn-default");
        }
        $(btn).removeClass("btn-default").addClass("btn-info");
    }
}
// 显示所有标签
function showAll(data) {
    const labels_list = $("#labels_list");
    if (labels_list == null)
        return;
    labels_list.html("");

    const p = $(document.createElement("p"));
    labels_list.append(p);
    const labels = data.result;
    p.text("共有 " + labels.length + " 标签。");
    const table = $(document.createElement("table"));
    labels_list.append(table);
    table.addClass("table");

    const thead = $(document.createElement("thead"));
    table.append(thead);
    const head_tr = $(document.createElement("tr"));
    thead.append(head_tr);
    head_tr.html('<th scope="col">#</th>' +
        '<th scope="col">名称</th>' +
        '<th scope="col">信息</th>' +
        '<th scope="col">上级ID</th>' +
        '<th scope="col">操作</th>');

    const tbody = $(document.createElement("tbody"));
    table.append(tbody);
    for (let label of labels) {
        let body_tr = $(document.createElement("tr"));
        tbody.append(body_tr);
        body_tr.html('<th scope="row">' + label.id + '</th>' +
            '<td>' + label.labelName + '</td>' +
            '<td>' + label.labelInfo + '</td>' +
            '<td>' + label.uplevelId + '</td>' +
            '<td><div class="btn-group">' +
            '<button class="btn btn-primary" onclick="updateModal(\'' + label.id + '\', \'' + label.labelName + '\', \'' + label.labelInfo + '\')">编辑</button>' +
            '<button class="btn btn-danger" onclick="confirmAction(del, ' + label.id + ')">删除</button>' +
            '</div></td>');
    }
}

function editMode() {
    if (edit_mode === 0)
        edit_mode = 1;
    else
        edit_mode = 0;

    if (edit_mode === 1) {
        for (let i = 1; i <= max_level; i++) {
            if ($("#label_" + i).attr("uplevel") !== undefined && $("#label_" + i).attr("uplevel") !== "")
            {
                $("#label_" + i).append('<button id="add_button_'+i+'" class="btn btn-success" onclick="addModal('+i+')">添加</button>');
            }
        }

        $("#edit_btn").text("退出编辑模式");
    } else {
        getAll();
        $("#edit_btn").text("进入编辑模式");
    }
}
